import apiRequest from '@/utils/apiRequest';

/**
 * 获取部门列表
 * @param {Object} params - 查询参数
 * @param {number} params.page - 页码
 * @param {number} params.pageSize - 每页数量
 */
export const getDepartments = async (params) => {
  try {
    const response = await apiRequest.get('/api/Departments', { params });
    return response.data;
  } catch (error) {
    console.error('Failed to get departments:', error);
    throw error;
  }
};

/**
 * 创建部门
 * @param {Object} departmentData - 部门数据
 * @param {string} departmentData.departmentName - 部门名称
 * @param {number|null} departmentData.parentDepartmentId - 上级部门ID
 * @param {string} departmentData.description - 部门描述
 */
export const createDepartment = async (departmentData) => {
  try {
    const response = await apiRequest.post('/api/Departments', departmentData);
    return response.data;
  } catch (error) {
    console.error('Failed to create department:', error);
    throw error;
  }
};

/**
 * 更新部门
 * @param {number} departmentId - 部门ID
 * @param {Object} departmentData - 部门数据
 * @param {string} departmentData.departmentName - 部门名称
 * @param {number|null} departmentData.parentDepartmentId - 上级部门ID
 * @param {string} departmentData.description - 部门描述
 */
export const updateDepartment = async (departmentId, departmentData) => {
  try {
    const response = await apiRequest.put(`/api/Departments/${departmentId}`, departmentData);
    return response.data;
  } catch (error) {
    console.error(`Failed to update department ${departmentId}:`, error);
    throw error;
  }
};

/**
 * 删除部门
 * @param {number} departmentId - 部门ID
 */
export const deleteDepartment = async (departmentId) => {
  try {
    const response = await apiRequest.delete(`/api/Departments/${departmentId}`);
    return response.data;
  } catch (error) {
    console.error(`Failed to delete department ${departmentId}:`, error);
    throw error;
  }
};

/**
 * 更新部门状态
 * @param {number} departmentId - 部门ID
 * @param {Object} statusData - 状态数据
 * @param {boolean} statusData.status - 部门状态
 */
export const updateDepartmentStatus = async (departmentId, statusData) => {
  try {
    const response = await apiRequest.patch(`/api/Departments/${departmentId}/status`, statusData);
    return response.data;
  } catch (error) {
    console.error(`Failed to update status for department ${departmentId}:`, error);
    throw error;
  }
};

/**
 * 搜索部门
 * @param {Object} searchParams - 搜索参数
 * @param {string} searchParams.departmentCode - 部门编码
 * @param {string} searchParams.departmentName - 部门名称
 * @param {string} searchParams.status - 部门状态
 * @param {number} searchParams.page - 页码
 * @param {number} searchParams.pageSize - 每页数量
 */
export const searchDepartments = async (searchParams) => {
  try {
    const response = await apiRequest.get('/api/Departments/search', { params: searchParams });
    return response.data;
  } catch (error) {
    console.error('Failed to search departments:', error);
    throw error;
  }
};